<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    title="添加发货通知单"
    width="60%"
    :close-on-click-modal="false"
    @close="handleClose">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="shipment-form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="通知单编号" prop="shipmentsCode">
            <el-input v-model="form.shipmentsCode" placeholder="请输入退货单编号">
              <template #append>
                <el-switch v-model="autoGenerate" active-text="自动生成" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="通知单名称" prop="shipmentsName">
            <el-input v-model="form.shipmentsName" placeholder="请输入通知单名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="销售订单编号" prop="saleCode">
            <el-input v-model="form.saleCode" placeholder="请输入销售订单编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户编码" prop="custCode">
            <el-input v-model="form.custCode" placeholder="请选择客户">
              <template #append>
                <el-button @click="openCustomerSelect">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发货日期" prop="shipmentsTime">
            <el-date-picker
              v-model="form.shipmentsTime"
              type="date"
              placeholder="请选择发货日期"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货人" prop="receivingName">
            <el-input v-model="form.receivingName" placeholder="请输入收货人" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="收货地址" prop="receivingAddress">
        <el-input v-model="form.receivingAddress" placeholder="请输入收货地址" />
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 客户选择对话框 -->
  <customer-select
    v-model:visible="customerSelectVisible"
    @select="handleCustomerSelect"
  />
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import http from '@/api/http'
import CustomerSelect from './CustomerSelect.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success'])

// 表单ref
const formRef = ref(null)

// 自动生成编号
const autoGenerate = ref(true)

// 监听自动生成开关
watch(autoGenerate, (newVal) => {
  if (newVal) {
    generateShipmentsCode()
  }
})

// 生成发货通知单编号
const generateShipmentsCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  form.shipmentsCode = `SN${year}${month}${day}${hours}${minutes}${seconds}`
}

// 初始化时生成编号
onMounted(() => {
  if (autoGenerate.value) {
    generateShipmentsCode()
  }
})

// 客户选择对话框
const customerSelectVisible = ref(false)

// 表单数据
const form = reactive({
  shipmentsCode: '',
  shipmentsName: '',
  saleCode: '',
  custCode: '',
  custName: '',
  shipmentsTime: '',
  receivingName: '',
  phone: '',
  receivingAddress: '',
  remark: '',
  state: 0
})

// 表单验证规则
const rules = {
  shipmentsName: [{ required: true, message: '请输入通知单名称', trigger: 'blur' }],
  custCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
  shipmentsTime: [{ required: true, message: '请选择发货日期', trigger: 'change' }],
  receivingName: [{ required: true, message: '请输入收货人', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  receivingAddress: [{ required: true, message: '请输入收货地址', trigger: 'blur' }]
}

// 打开客户选择
const openCustomerSelect = () => {
  customerSelectVisible.value = true
}

// 处理客户选择
const handleCustomerSelect = (customer) => {
  form.custCode = customer.custCode
  form.custName = customer.custName
}

// 处理保存
const handleSave = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error('表单验证失败:', fields)
      return
    }

    try {
      const res = await http.post('/api/ShipmentsModel/AddShipmentsModel', form)
      if (res.status === true) {
        ElMessage.success('添加成功')
        emit('success')
        handleClose()
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    } catch (error) {
      console.error('添加失败:', error)
      ElMessage.error('添加失败')
    }
  })
}

// 处理关闭
const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}
</script>

<style scoped>
.shipment-form {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-form-item__content) {
  flex-wrap: nowrap;
}
</style> 